<template>
	<view class="OrderDetails-box" :class="{'no-scroll': isPopupOpen}">
		<view class="header-box">
			<view class="ToBePaid-box" v-if="hotelOrderDetail.state_order==1">
				<text class="order-state" style="color: #e63345;">待支付</text>
				<text class="order-state-describe" style="color: #e63345;">剩余支付时间：{{ countdownTime }}</text>
			</view>
			<view class="ToBePaid-box" v-if="hotelOrderDetail.state_order==2">
				<text class="order-state" style="color: #fff;">待出行</text>
				<text class="order-state-describe" style="color: #fff;">启程在即,让西望和您一起迎接即将到来的精彩时刻!</text>
			</view>
			<view class="success-box" v-if="hotelOrderDetail.state_order==3">
				<text class="order-state">已出行</text>
				<text class="order-state-describe">西望期待与你的下次相遇</text>
			</view>
			<view class="ToBePaid-box" v-if="hotelOrderDetail.state_order==4">
				<text class="order-state">退款中</text>
				<text class="order-state-describe">我们将在三个工作日内退回费用</text>
			</view>
			<view class="ToBePaid-box" v-if="hotelOrderDetail.state_order==5">
				<text class="order-state">交易完成</text>
				<text class="order-state-describe">西望期待与你的下次相遇</text>
			</view>
			<view class="success-box" v-if="hotelOrderDetail.state_order==6">
				<text class="order-state">退款成功</text>
				<text class="order-state-describe">西望期待与你的下次相遇</text>
			</view>
			<view class="success-box" v-if="hotelOrderDetail.state_order==7">
				<text class="order-state">拒绝退款</text>
				<text class="order-state-describe">西望期待与你的下次相遇</text>
			</view>
		</view>
		<view class="content-box">
			<view class="Order-info-card" @click="toShopDetails(hotelOrderDetail?.trip_shops_id)">
				<image class="card-img" :src="imageUrl + hotelOrderDetail.shop_cover_img" mode="aspectFill"></image>
				<view class="card-content-right">
					<text class="title">{{hotelOrderDetail.shop_main_title}}</text>
					<text class="description">{{hotelOrderDetail.order_detail}}</text>
					<text class="travel_date">出行时间：{{formatDate(hotelOrderDetail.travel_date)}}</text>
					<view class="Number-box">
						<text>人数：</text>
						<text class="Number">×{{hotelOrderDetail.order_traveler_list.length}}</text>
					</view>
				</view>
			</view>

			<view class="info-card">
				<text class="box-title">出行人</text>
				<view class="traveler-content">
					<view class="traveler-info" v-for="(item , index) in hotelOrderDetail.order_traveler_list">
						<text class="name">{{item.travelers_name}}</text>
						<text>身份证 {{item.travelers_card_number}}</text>
						<text>{{item.travelers_phone}}</text>
					</view>
				</view>
			</view>
			<view class="info-card">
				<text class="box-title">费用明细</text>
				<view class="Order-Info flex-space-between">
					<view>
						<text class="title">订单总价</text>
						<text class="content">￥{{hotelOrderDetail.all_cost}}</text>
					</view>
					<view>
						<text class="title">含人数数</text>
						<text class="content">{{hotelOrderDetail.order_traveler_list.length}}人</text>
					</view>
					<view>
						<text class="title">含房间数</text>
						<text class="content">{{hotelOrderDetail.hotel_number}}间</text>
					</view>
					<view>
						<text class="title">含房差费</text>
						<text class="content">￥{{hotelOrderDetail.order_difference_rate}}</text>
					</view>
					<view>
						<text class="title" style="color: #000;">实付款</text>
						<text class="content"
							style="font-weight: 600; font-size: 30rpx;">￥{{hotelOrderDetail.all_cost}}</text>
					</view>
				</view>
			</view>

			<view class="info-card">
				<text class="box-title">订单信息</text>
				<view class="Order-Info flex-space-between">
					<view>
						<text class="title">订单号</text>
						<text class="content">{{hotelOrderDetail.transaction_id || '暂未支付'}}</text>
					</view>
					<view>
						<text class="title">下单时间</text>
						<text class="content">{{hotelOrderDetail.order_create_time}}</text>
					</view>
					<view>
						<text class="title">联系人</text>
						<text class="content">{{hotelOrderDetail.order_username}}
							{{hotelOrderDetail.order_phone}}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="card-bottom">
			<button open-type="contact" session-from="userPage">联系客服</button>
			<button class="refund-button" v-if="[2,7].includes(parseInt(hotelOrderDetail.state_order))"
				@click="openPopupInParent">申请退款</button>
			<button v-if="!hotelOrderDetail.if_state_pay" class="Pay-Now"
				@click="orderNowPay(hotelOrderDetail.order_id)">立即付款</button>
			<button v-if="[3].includes(parseInt(hotelOrderDetail.state_order))" class="Pay-Now"
				@click="ConfirmOrder">确认订单</button>
		</view>
	</view>
	<RefundPopupVue ref="childPopup" :Id="orderId" @openPopup="handleOpenPopup" @closePopup="handleClosePopup" />
</template>

<script setup>
	import {
		imageUrl
	} from '@/config/request/request.js'
	import {
		ref
	} from 'vue';
	import {
		formatDate
	} from '@/config/CaDateObject.js'
	import {
		getOrdersDetail,
		putOrderConfirm
	} from '@/config/API/Orders.js';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		wechatPay
	} from '@/config/API/ProductDetails.js'

	import RefundPopupVue from './components/RefundPopup.vue';
	const hotelOrderDetail = ref()
	const countdownTime = ref(); // 倒计时剩余时间
	// 父组件中引用子组件
	const childPopup = ref(null);
	const isPopupOpen = ref(false);
	const orderId = ref()
	// 打开子组件的弹窗方法
	const openPopupInParent = () => {
		if (childPopup.value) {
			childPopup.value.openPopup();
		}
	};
	// 监听子组件的事件来处理其他逻辑
	const handleOpenPopup = () => {
		console.log('弹窗打开');
		isPopupOpen.value = true;
	};

	const handleClosePopup = () => {
		console.log('弹窗关闭');
		isPopupOpen.value = false;
		getData(orderId.value)
	};
	onLoad((Option) => {
		console.log('Option.orderId', Option.orderId);
		orderId.value = Option.orderId
		getData(orderId.value)
	})

	const getData = async (orderId) => {
		try {
			// 获取订单详情数据
			const resHotelOrde = await getOrdersDetail(orderId);
			hotelOrderDetail.value = resHotelOrde.data;
			// console.log('订单详情数据', hotelOrderDetail.value);
			// 解析 order_traveler_list 字符串
			if (hotelOrderDetail.value && hotelOrderDetail.value.order_traveler_list) {
				// 将字符串解析为对象（数组）
				const travelersList = JSON.parse(hotelOrderDetail.value.order_traveler_list);
				console.log('解析后的旅客列表:', travelersList);
				hotelOrderDetail.value.order_traveler_list = travelersList;
			}
			if (hotelOrderDetail.value && hotelOrderDetail.value.order_create_time) {
				if (!hotelOrderDetail.value.if_state_pay) {
					startCountdown(hotelOrderDetail.value.order_create_time);
				}
			}
			// peopleNumber.value = hotelOrderDetail.value.order_traveler_list.length
			console.log('订单详情数据', hotelOrderDetail.value);
		} catch (error) {
			console.error('获取订单数据失败', error);
		}
	}
	// 倒计时函数
	// 格式化日期字符串
	const formatOrderCreateTime = (orderCreateTime) => {
		return orderCreateTime.replace(/-(\d{2}):(\d{2})$/, "T$1:$2:00");
	};

	// 倒计时函数
	const startCountdown = (orderCreateTime) => {
		// 格式化日期字符串
		const formattedTime = formatOrderCreateTime(orderCreateTime);

		// 解析日期（假设 orderCreateTime 是本地时间，不需要调整）
		const orderTime = new Date(formattedTime).getTime();

		// 计算结束时间（30 分钟后）
		const endTime = orderTime + 30 * 60 * 1000;

		const updateCountdown = () => {
			const currentTime = new Date().getTime(); // 当前时间戳
			const remainingTime = endTime - currentTime; // 剩余时间（毫秒）

			if (remainingTime <= 0) {
				countdownTime.value = "已超时"; // 倒计时结束
				return;
			}

			// 计算剩余分钟和秒
			const minutes = Math.floor(remainingTime / (1000 * 60));
			const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

			// 格式化为两位数字，例如 "01:05"
			countdownTime.value = `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;

			// 每秒更新一次
			setTimeout(updateCountdown, 1000);
		};

		updateCountdown();
	};

	// 用户确认订单
	const ConfirmOrder = async () => {
		const userId = uni.getStorageSync('userInfo').id;
		const OrderConfirmForm = {
			order_id: parseInt(orderId.value),
			user_id: userId,
		};
		try {
			const resInfo = await putOrderConfirm(OrderConfirmForm);
			console.log('确认订单返回信息', resInfo);
			if (resInfo.code == 200) {
				getData(orderId.value)
				uni.showToast({
					title: '确认成功，西望期待与你的下次相遇',
					icon: 'none',
					duration: 2000
				});
			} else {
				uni.showToast({
					title: '订单确认失败',
					icon: 'none',
				});
			}
		} catch (error) {
			console.error('确认订单失败', error);
			uni.showToast({
				title: '确认订单失败，请稍后再试',
				icon: 'none',
			});
		}
	};
	// 订单支付
	const orderNowPay = async (orderId) => {
		const openId = uni.getStorageSync('userInfo').openID
		const itForm = {
			order_id: orderId,
			openid: openId
		}
		try {
			const resPay = await wechatPay(itForm)
			if (resPay.code == 200) {
				console.log('resPay.data', resPay.data);
				uni.requestPayment({
					provider: "wxpay",
					...resPay.data,
					success: async (res) => {
						console.log(res);
						uni.hideLoading();
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 1500
						});
						// 延迟 2 秒后再跳转
						setTimeout(() => {
							getData(orderId)
						}, 1000);
					},

					fail: (err) => {
						console.log(err);
						// 支付失败后的操作
						// 例如，提示用户支付失败

						uni.showToast({
							title: '支付失败，请重试',
							icon: 'error'
						});
						// 隐藏加载提示
						uni.hideLoading();
					},
				});
			} else {
				uni.showToast({
					title: '订单异常',
					icon: 'none'
				})
				// 隐藏加载提示
				uni.hideLoading();
			}
		} catch (e) {
			uni.showToast({
				title: '未知错误请稍后再试 ',
				icon: 'none'
			})
			uni.hideLoading();
		}
	}
	const toShopDetails = (id) => {
		uni.navigateTo({
			url: `/homeSubpages/ProductDetails/index?ShopId=${id}`
		})
	}
</script>

<style lang="scss" scoped>
	.no-scroll {
		overflow: hidden;
		position: fixed;
		width: 100%;
		height: 100%;
	}
	.OrderDetails-box {
		width: 100%;
		min-height: 100vh;

		.header-box {
			width: 100%;
			height: 240rpx;
			background-color: #7f7c72;
			padding: 0rpx 50rpx;
			padding-top: 20rpx;
			box-sizing: border-box;

			view {
				display: flex;
				flex-direction: column;
				gap: 15rpx;

				text {
					color: #fff;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					overflow: hidden;
					text-overflow: ellipsis;
					-webkit-line-clamp: 1;
					letter-spacing: 2rpx;
				}

				.order-state {
					font-size: 30rpx;
					font-weight: 500;
				}

				.order-state-describe {
					font-size: 24rpx;
					font-weight: 400;
				}
			}
		}

		.content-box {
			width: 100%;
			min-height: calc(100vh - 240rpx);
			display: flex;
			flex-direction: column;
			gap: 30rpx;
			padding: 30rpx;
			padding-bottom: 180rpx;
			box-sizing: border-box;
			background-color: #f5f6f7;

			.Order-info-card {
				width: 100%;
				display: flex;
				justify-content: space-between;
				background-color: #fff;
				border-radius: 20rpx;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				margin-top: -130rpx;

				.card-img {
					min-width: 36%;
					max-width: 36%;
					height: 180rpx;
					border-radius: 10rpx;
				}

				.card-content-right {
					min-width: 58%;
					max-width: 58%;
					display: flex;
					flex-direction: column;
					gap: 15rpx;

					text {
						display: -webkit-box;
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.title {
						-webkit-line-clamp: 2;
						font-weight: 600;
						font-size: 28rpx;
					}

					.description {
						-webkit-line-clamp: 1;
						font-size: 26rpx;
						color: #8a8a8a;
					}

					.travel_date {
						-webkit-line-clamp: 1;
						font-size: 26rpx;
						color: #8a8a8a;
					}

					.Number-box {
						width: 100%;
						padding: 10rpx 20rpx;
						box-sizing: border-box;
						display: flex;
						justify-content: flex-end;
						align-items: flex-end;

						text {
							color: #8a8a8a;
							font-size: 26rpx;
							font-weight: 200;
						}
					}
				}
			}

			.info-card {
				width: 100%;
				background-color: #fff;
				border-radius: 20rpx;
				padding: 0 0 20rpx 0rpx;
				box-sizing: border-box;

				.box-title {
					width: 100%;
					display: block;
					border-bottom: 2rpx solid #f5f6f7;
					padding: 20rpx 30rpx;
					box-sizing: border-box;
					font-size: 30rpx;
				}

				.traveler-content {
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					gap: 50rpx;
					padding: 20rpx 30rpx;
					box-sizing: border-box;

					.traveler-info {
						max-width: 390rpx;
						min-width: 390rpx;
						display: flex;
						flex-direction: column;
						gap: 8rpx;

						text {
							color: #8a8a8a;
							font-size: 28rpx;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							overflow: hidden;
							text-overflow: ellipsis;
							-webkit-line-clamp: 1;
						}

						.name {
							color: #000;
							font-size: 30rpx;
						}
					}
				}

				.flex-space-between {
					display: flex;
					flex-direction: column;
					gap: 26rpx;
					padding: 20rpx 30rpx;
					box-sizing: border-box;

					>view {
						display: flex;
						justify-content: space-between;

						text {
							font-size: 28rpx;
							color: #000;
							font-weight: 500;
						}

						.title {
							color: #8a8a8a;
						}
					}
				}
			}
		}

		.card-bottom {
			position: fixed;
			bottom: 0;
			width: 100%;
			height: 130rpx;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			gap: 20rpx;
			padding: 0 30rpx;
			padding-bottom: 20rpx;
			box-sizing: border-box;
			background-color: #fff;
			border-top: 2rpx solid #f5f6f7;

			button {
				width: 150rpx;
				height: 60rpx;
				line-height: 60rpx;
				background-color: transparent;
				padding: 0;
				margin: 0;
				font-size: 26rpx;
				border: 1rpx solid #cccccc;

				&::after {
					border: none;
				}
			}

			.refund-button {
				color: #fc394b;
				border: 1rpx solid #fc394b;
			}

			.Pay-Now {
				color: #fff;
				background-color: #000;
				border: 1rpx solid #000;
			}
		}
	}
</style>